import { ref, onUnmounted } from "vue";
import { WebSocketClient } from "@/utils/websocket";
import type { WebSocketConfig, ApiResponse } from "@/types/websocket";

export function useWebSocket(url: string, config?: WebSocketConfig) {
  if (!url) {
    throw new Error("WebSocket URL is required");
  }

  const socket = ref<WebSocketClient | null>(null);
  const WSmessages = ref<any[]>([]);
  const isConnected = ref(false);

  const connect = (customConfig?: WebSocketConfig) => {
    console.log("链接了。。。。调用leconnect");

    // 合并配置，确保 onOpen 逻辑正确
    const mergedConfig = {
      ...config,
      ...customConfig,
      onOpen: () => {
        isConnected.value = true;
        config?.onOpen?.();
        customConfig?.onOpen?.();
      },
    };

    socket.value = new WebSocketClient(url, {
      maxReconnectAttempts: mergedConfig.maxReconnectAttempts || 10,
      reconnectInterval: mergedConfig.reconnectInterval || 3000,
      onMessage: mergedConfig.onMessage,
      onError: mergedConfig.onError,
      onClose: mergedConfig.onClose,
      onOpen: mergedConfig.onOpen,
    });

    socket.value.addMessageHandler((data: any) => {
      WSmessages.value.push(data);
      mergedConfig.onMessage?.(data);
    });
    // 检查 onError 是否存在
    if (mergedConfig.onError) {
      socket.value.addErrorHandler(mergedConfig.onError);
    }

    socket.value.addCloseHandler((event: CloseEvent) => {
      isConnected.value = false;
      mergedConfig.onClose?.(event);
    });

    socket.value.connect();
  };

  const send = (data: any) => {
    if (socket.value && isConnected.value) {
      console.log(data, "wsdata");
      socket.value.send({ code: "play", data: data });
    }
  };

  /*   const close = () => {
    if (socket.value) {
      socket.value.send({ code: "stop", data: "" });
      socket.value.close();
    }
  }; */
  const closews = () => {
    console.log("closews");
    if (socket.value) {
      try {
        socket.value.send({ code: "stop", data: "" });
        socket.value.close();
      } catch (error) {
        console.log("socket null");
        console.error("Error closing WebSocket connection:", error);
      } finally {
        socket.value = null; // 清理引用
        isConnected.value = false;
      }
    }
  };
  const stop = () => {
    console.log("stop");
    if (socket.value) {
      socket.value.send({ code: "stop", data: "" });
    } else {
      console.log("socket null");
    }
  };
  onUnmounted(() => {
    closews();
  });

  return {
    WSmessages,
    isConnected,
    connect,
    send,
    closews,
    stop,
  };
}
